package ltq.telphoneAgeAverage.loadintoDatabase;

import sgt.test.util.DatabaseUtil;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class LoadIntoDatabase {
    public static void main(String[] args) {
        LoadIntoDatabase loadIntoDatabase=new LoadIntoDatabase();
        loadIntoDatabase.writeIntoDataBase();
    }

    public void writeIntoDataBase(){
        String dir = "src/main/resources/ltqdata/electronicsWashed.csv";
        File file = new File(dir);
        Connection con=null;
        PreparedStatement ps=null;
        int rows=0;
        con= DatabaseUtil.getConnection();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            br.readLine();
            while ((line=br.readLine())!=null) {
                String[] partitions=line.split(",");
                ps=con.prepareStatement("insert into TAAdata(Tid,event_time,order_id,product_id,category_id,category_code,Tbrand,Tprice,Tuser_id,Tage,Tsex,Tlocal) values (?,?,?,?,?,?,?,?,?,?,?,?)");
                for (int i=1;i<=12;i++){
                    ps.setObject(i,partitions[i-1]);
                }
                rows=ps.executeUpdate();
            }
            br.close();
            //指定要执行的sql语句，创建一个PreparedStatement对象，用于操作该sql语句

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally{
            //finally模块的代码不管try中是否出现异常，都会被执行，通常用于关闭一些资源的占用
            DatabaseUtil.close(null, ps, con);
        }
    }
}
